package com.juzipi.demo.utils;


import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;

/**
 * token工具类
 */

public class JwtUtil {

    public static final long EXPIRE_TIME = 5*60*1000;//token到期时间毫秒为单位
    public static final long REFRESH_EXPIRE_TIME = 30*60;//refreshToken到期时间30分钟
    public static final String TOKEN_SALT = "qwertyuiop";


    /**
     * 生成token
     * @param username
     * @param currentTime
     * @return
     */
    public static String getToken(String username,Long currentTime){
        String token = null;
        try {
            Date expire = new Date(currentTime + EXPIRE_TIME);
            token = JWT.create()
                    .withIssuer("auth0")//发行人
                    .withClaim("username", username)
                    .withClaim("currentTime", currentTime)
                    .withExpiresAt(expire)//过期时间
                    .sign(Algorithm.HMAC256(TOKEN_SALT));
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (JWTCreationException e) {
            e.printStackTrace();
        }
        return token;
    }


    /**
     * 验证token
     * @param token
     * @return
     * @throws Exception
     */
    public static boolean verify(String token) throws Exception{
        DecodedJWT auth0 = JWT.require(Algorithm.HMAC256(TOKEN_SALT)).withIssuer("auth0").build().verify(token);
        System.out.println("===================>  通过了认证");
        System.out.println("username: "+auth0.getClaim("username").asString());
        System.out.println("过期时间： "+auth0.getExpiresAt());
        return true;
    }



    public static String getUsername(String token){
        try {
            DecodedJWT decode = JWT.decode(token);
            return decode.getClaim("username").asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }


    //获取当前时间
    public static Long getCurrentTime(String token){
        try {
            DecodedJWT decode = JWT.decode(token);
            return decode.getClaim("currentTime").asLong();
        } catch (JWTDecodeException e) {
            return null;
        }
    }


}
